package com.yk.framework.db;

import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;

import com.yk.framework.common.StringUtils;
import com.yk.framework.entity.ICoreBaseInfo;
import com.yk.framework.entity.impl.CoreBaseCollection;

/**
 * @author lifetime
 * 
 */
public class DBFacade {

	private static final Logger logger = Logger.getLogger(DBFacade.class);

	public static ICoreBaseInfo getInfoByID(String id) {
		return DBPool.getInstance().getCoreBaseInfoByID(id);
	}

	public static ICoreBaseInfo getInfoBySql(String sql, Object[] params) {
		return DBPool.getInstance().getCoreBaseInfoBySql(sql, params);
	}

	public static CoreBaseCollection getCollectionBySql(String sql, Object[] params) {
		return DBPool.getInstance().getCoreBaseCollectionBySql(sql, params);
	}

	public static boolean delete(String id) {
		return DBPool.getInstance().delete(id);
	}

	public static String save(ICoreBaseInfo info) {
		if (StringUtils.isEmpty(info.getString("id"))) {
			return addnew(info);
		} else {
			return update(info);
		}
	}

	public static String update(ICoreBaseInfo info) {
		String id = info.getString("id");
		String table = YKIDUtils.getTable(id);
		StringBuffer sql = new StringBuffer("update " + table + " set ");
		Set<String> keys = info.keys();
		Object[] params = new Object[keys.size() + 1];
		int i = 0;
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			String key = (String) it.next();
			if (i == params.length - 2) {
				sql.append(key).append("=?");
			} else {
				sql.append(key).append("=?,");
			}
			params[i] = handleValue(info.get(key));
			i++;
		}
		sql.append(" where id = ?");
		params[params.length - 1] = id;
		DBPool.getInstance().execute(sql.toString(), params);
		return id;
	}

	public static String addnew(ICoreBaseInfo info) {
		String id = YKIDUtils.generateID(info.getYKEntityType());
		String table = YKIDUtils.getTable(id);
		info.put("id", id);
		StringBuffer sql = new StringBuffer("insert  into  " + table + " ( ");
		Set<String> keys = info.keys();
		Object[] params = new Object[keys.size()];
		int i = 0;
		StringBuffer valuesString = new StringBuffer();
		for (Iterator<String> it = keys.iterator(); it.hasNext(); i++) {
			String key = (String) it.next();
			if (i == params.length - 1) {
				sql.append(key);
				valuesString.append("?");
			} else {
				sql.append(key).append(",");
				valuesString.append("?,");
			}
			params[i] = handleValue(info.get(key));
		}
		sql.append(") values(").append(valuesString).append(")");
		DBPool.getInstance().execute(sql.toString(), params);
		return id;
	}

	protected static Object handleValue(Object obj) {
		if (obj != null) {
			if (obj instanceof ICoreBaseInfo) {
				return ((ICoreBaseInfo) obj).getString("id");
			}
		}
		return obj;
	}
}
